package com.ruoyi.common.filter.util;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.filter.recode.CommonReturnCode;
import com.ruoyi.common.filter.response.ServerResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class SignUtils {

    /**
     * 网关抛异常
     */
    public static void getException(HttpServletRequest request, HttpServletResponse response, CommonReturnCode returnCode) throws IOException {
        String message = errorMessage(request, returnCode, returnCode.getMsg());
        if (returnCode == CommonReturnCode.GATEWAY_TOKEN_ABSENT || returnCode == CommonReturnCode.GATEWAY_CHECK_SIGN_FAIL) {
            // 网关验签失败和Token不存在的异常，日志输出级别为WARN
            log.warn(message);
        } else {
            log.error(message);
        }

        // 构造返回对象
        // 处理浏览器访问时中文乱码的问题
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(JSONUtil.toJsonStr(ServerResponseEntity.fail(returnCode.getCode(), returnCode.getMsg())));
    }

    /**
     * 获取标准格式的异常日志输出
     * 格式：({错误码}){错误码英文}:{错误码描述}『接口请求信息』服务器信息『异常信息』"
     *
     * @param request
     * @param returnCode
     * @param errorMessage
     * @return
     */
    public static String errorMessage(HttpServletRequest request, CommonReturnCode returnCode, String errorMessage) {
        StringBuilder errMsg = new StringBuilder();
        errMsg.append("(").append(returnCode.getCode()).append(")").append(returnCode.name()).append(":").append(returnCode.getMsg());
        errMsg.append("『");
        errMsg.append(request.getMethod()).append(" ").append(request.getRequestURI());
        if (StringUtils.isNotEmpty(request.getQueryString())) {
            errMsg.append("?").append(request.getQueryString());
        }
        errMsg.append("』");
        errMsg.append("终端类型：").append(request.getHeaders("clientType"));
        errMsg.append(",");
        errMsg.append("终端版本：").append(request.getHeaders("clientVersion"));
        errMsg.append(",");
        errMsg.append("用户标识：").append(request.getHeaders("userId"));
        errMsg.append(",");
        errMsg.append("终端地址：").append(request.getHeaders("X-Forwarded-For"));
        errMsg.append(" > ");
        errMsg.append(errorMessage);

        return errMsg.toString();
    }

}
